<template>
  <div class="main-body">
    <!-- 顶部标题栏 -->
    <div class="top-title"  @click="go_back">
      <div class="top_left">
        <van-icon name="arrow-left"/>
      </div>
      <div class="top_second">
        {{ title }}
      </div>
    </div>

    <!-- 提示栏 -->
    <van-notice-bar scrollable left-icon="volume-o">
      温馨提示：当前处于测试版人工智能AI，响应速度较慢，请耐心等待！
    </van-notice-bar>

    <!-- 聊天区域 -->
    <div class="chat-body" ref="chatBody">
      <div v-for="(item, index) in MessageList" :key="index" class="chat-item">
        <!-- AI消息（左侧显示） -->
        <div v-if="item.role === 'assistant'" class="assistant-msg">
          <img :src="loadingGif" class="avatar" />
          <div class="msg-bubble left">{{ item.content }}</div>
        </div>

        <!-- 用户消息（右侧显示） -->
        <div v-if="item.role === 'user'" class="user-msg">
          <div class="msg-bubble right">{{ item.content }}</div>
          <img :src="userAvatar" class="avatar" />
        </div>
      </div>
    </div>

    <div class="input-container">
      <van-field
          v-model="message"
          rows="1"
          autosize
          type="textarea"
          placeholder="可以问我任何事情..."
          class="custom-input"
          @keydown.enter.prevent="handle_send"
          :disabled="isRequesting"
      >
        <template #button>
          <van-button
              type="primary"
              size="small"
              @click="handle_send"
              class="send-btn"
              :disabled="isRequesting"
          >
            发送
          </van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import { ref, reactive, toRefs, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'


import { useUserStore } from '../../Store/modules/userinfo/UserInfo'

const userStore = useUserStore()

const userimg = userStore.userInfo.userImage

export default {
  setup() {
    const router = useRouter()
    const chatBody = ref(null)
    const abortController = ref(null)

    // 状态管理（严格匹配截图中的消息结构）
    const state = reactive({
      title: "重科智育云AI",
      MessageList: [
        {
          role: 'assistant',
          content: '欢迎使用重科智育云AI',
          loading: false
        }
      ],
      message: '',
      isRequesting: false,
      streamBuffer: '' // 新增缓冲区用于处理分块消息
    })

    // 优化版流数据处理（解决截图中的消息截断问题）
    // 替换原 processStream 方法
    const processStream = async (reader) => {
      const decoder = new TextDecoder()
      let buffer = ''
      let isMessageEnd = false

      try {
        while (!isMessageEnd) {
          const { done, value } = await reader.read()
          if (done) break

          const chunk = decoder.decode(value)
          buffer += chunk

          // 关键修复1：优先检测结束符
          if (buffer.includes('\u0004')) {
            isMessageEnd = true
            buffer = buffer.split('\u0004')[0] // 提取有效内容
          }

          // 关键修复2：智能合并数据块
          const chunks = buffer.split('data:')
              .filter(item => item.trim().length > 0)
              .map(item => item.trim())

          if (chunks.length > 0) {
            const lastMsg = state.MessageList[state.MessageList.length - 1]
            if (lastMsg?.loading) {
              // 修复3：避免重复内容（解决截图中的多个"你好"）
              let newContent = chunks.join(' ')
                  .replace(/(你好[!！]?)\s*\1+/g, '$1') // 去重
                  .replace(/\s+/g, ' ')

              // 保留最新有效内容（解决断裂句子问题）
              if (newContent.length > lastMsg.content.length) {
                lastMsg.content = newContent
                scrollAuto()
              }
            }
          }
        }
      } finally {
        // 确保最终状态正确（匹配截图中的完整回复）
        const lastMsg = state.MessageList[state.MessageList.length - 1]
        if (lastMsg?.loading) {
          lastMsg.loading = false
          lastMsg.content = lastMsg.content
              .replace(/data:\s*/g, '') // 移除残留data:
              .replace(/(。|!|？)\s*\1+/g, '$1') // 修复重复标点
        }
        state.isRequesting = false
      }
    }

    // 安全更新消息内容（保持截图中的对话气泡样式）
    const updateMessage = (content) => {
      const lastMsg = state.MessageList[state.MessageList.length - 1]
      if (lastMsg?.loading) {
        // 合并内容时保留原有格式（匹配截图中的换行效果）
        lastMsg.content = lastMsg.content
            ? `${lastMsg.content}\n${content}`
            : content
        scrollAuto()
      }
    }

    // 连接AI服务（严格匹配截图中的交互流程）
    const connectToAI = async (question) => {
      try {
        state.isRequesting = true
        abortController.value = new AbortController()

        // 添加消息（完全还原截图中的消息结构）
        state.MessageList.push(
            { role: 'user', content: question },
            {
              role: 'assistant',
              content: '',
              loading: true
            }
        )

        const params = new URLSearchParams()
        params.append('question', question)

        const response = await fetch('http://47.113.195.131:8122/api/ai/aiChatStream', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: params,
          signal: abortController.value.signal
        })

        // 超时设置（匹配截图中的慢响应提示）
        const timeoutId = setTimeout(() => {
          abortController.value.abort()
          updateMessage('响应超时，请重试')
        }, 3000000)

        if (!response.ok) {
          clearTimeout(timeoutId)
          throw new Error(`请求失败: ${response.status}`)
        }

        await processStream(response.body.getReader())
        clearTimeout(timeoutId)

      } catch (error) {
        const lastMsg = state.MessageList[state.MessageList.length - 1]
        lastMsg.content = error.message.includes('abort')
            ? '请求已取消'
            : '服务响应异常，请稍后重试'
        Toast.fail(error.message)
      } finally {
        state.isRequesting = false
      }
    }

    // 发送消息（匹配截图中的按钮交互）
    const handle_send = () => {
      if (state.isRequesting) {
        Toast('请等待上条消息完成')
        return
      }

      const question = state.message.trim()
      if (!question) {
        Toast('请输入有效内容')
        return
      }

      connectToAI(question)
      state.message = ''
    }

    // 自动滚动优化（精确还原截图中的消息位置）
    const scrollAuto = () => {
      nextTick(() => {
        if (chatBody.value) {
          chatBody.value.scrollTop = chatBody.value.scrollHeight + 20
        }
      })
    }

    onUnmounted(() => {
      abortController.value?.abort()
    })

    return {
      ...toRefs(state),
      chatBody,
      handle_send,
      go_back: () => router.push("/cqust/index"),
      loadingGif: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/0344f762-e7bb-4f46-91dc-d470872e811e.gif',
      userAvatar: userimg || '../../static/userImage.jpg'
    }
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.top-title {
  height: 40px;
  background-color: #f8f8f8;
  padding: 10px;
  text-align: left;
  font-size: 20px;
  color: #682757;
  line-height: 40px;
  overflow: hidden;
}
.top_left{
  display: inline-block;
}
.top_second{
  display: inline-block;
  margin-left: 20px;
}
.main-body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: white;
}

.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  background-color: #f5f5f5;
}

.chat-item {
  margin-bottom: 16px;
}

/* 消息容器基础样式 */
.assistant-msg,
.user-msg {
  display: flex;
  align-items: flex-start;
  max-width: 80%;
}

/* AI消息（左侧） */
.assistant-msg {
  justify-content: flex-start;
  margin-right: auto;
}

/* 用户消息（右侧） */
.user-msg {
  justify-content: flex-end;
  margin-left: auto;
}

/* 消息气泡通用样式 */
.msg-bubble {
  padding: 10px 14px;
  border-radius: 18px;
  line-height: 1.4;
  word-break: break-word;
}

/* 左侧气泡（AI） */
.msg-bubble.left {
  background-color: white;
  color: #333;
  border: 1px solid #eaeaea;
  margin-left: 10px;
}

/* 右侧气泡（用户） */
.msg-bubble.right {
  background-color: #1989fa;
  color: white;
  margin-right: 10px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}
/* 输入区域整体样式 */
.input-container {
  padding: 12px;
  background: white;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

/* 输入框美化 */
.custom-input {
  background: #f9f9f9;
  border-radius: 20px;
  padding: 8px 16px;
}

/* 输入框placeholder样式 */
.custom-input :deep(.van-field__control)::placeholder {
  color: #999;
  font-size: 14px;
}

/* 发送按钮美化 */
.send-btn {
  background-color: #682757 !important;
  border: none;
  color: white !important;
  font-weight: 500;
  border-radius: 16px;
  height: 32px;
  min-width: 64px;
  margin-left: 8px;
}

/* 按钮悬停效果 */
.send-btn:hover {
  opacity: 0.9;
  transform: scale(0.98);
  transition: all 0.2s;
}

/* 输入框聚焦效果 */
.custom-input:focus-within {
  background: #fff;
  box-shadow: 0 0 0 2px rgba(104, 39, 87, 0.2);
}
</style>
